package common.utils;
import java.io.BufferedReader;
import java.io.IOException;  
import java.io.InputStreamReader;  
import java.io.UnsupportedEncodingException;  
import java.net.MalformedURLException;  
import java.net.URL;  
import java.net.URLConnection;  
import java.net.URLEncoder;
import java.util.Map;

import net.sf.json.JSONObject;  
public class BaiDuApi {
	//根据城市获取天气信息的java代码  
	//cityName 是你要取得天气信息的城市的中文名字，如“北京”，“深圳”  
	public static String  getWeatherInform(String cityName){  
	//百度天气API  
//	 JSONObject dataOfJson = JSONObject.fromObject(strPar);  
	String baiduUrl = null;
	try {
	baiduUrl = "http://api.map.baidu.com/telematics/v3/weather?location="+URLEncoder.encode(cityName, "utf-8")+"&output=json&ak=166501e88677959f3d16231094fd5283";
	} catch (UnsupportedEncodingException e1) {
	// TODO Auto-generated catch block
	e1.printStackTrace();
	}  
	StringBuffer strBuf;  
	strBuf = new StringBuffer();  
	try{  
	    URL url = new URL(baiduUrl);  
	    URLConnection conn = url.openConnection();  
	    BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream(),"utf-8"));//转码。  
	    String line = null;  
	    while ((line = reader.readLine()) != null)  
	        strBuf.append(line + " ");  
	        reader.close();  
	}catch(MalformedURLException e) {  
	    e.printStackTrace();   
	}catch(IOException e){  
	    e.printStackTrace();   
	}     

	return strBuf.toString();  
	}  

	public static void main(String[] args){
	BaiDuApi baidu = new BaiDuApi();
	System.out.println(baidu.getWeatherInform("深圳"));
	}
	
	/**
	 * 获取天气信息转成实时的温度湿度MAP
	 * @param resultString
	 * @return
	 */
	private static  Map<String , Object> strToMap (String resultString){
		 JSONObject dataOfJson = JSONObject.fromObject(resultString); 
		 if(dataOfJson.getInt("error")!=0){  
             return null;  
         }
		 JSONObject resultJson = dataOfJson.getJSONObject("results");
		 JSONObject weatherata = dataOfJson.getJSONObject("weather_data");
		return null;
		
	}
}